package com.erp.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.Utils.DateFormat;
import com.erp.Utils.ResponseModel;
import com.erp.entity.Demand;
import com.erp.entity.Label;
import com.erp.entity.Project;
import com.erp.service.DemandService;
import com.erp.service.LabelService;
import com.erp.service.ProjectService;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 需求录入表 前端控制器
 * </p>
 *
 * @author CJ
 * @since 2021-08-19
 */
@RestController
@RequestMapping("/demand")
public class DemandController {
    @Resource
    ProjectService projectService;
    @Resource
    LabelService labelService;
    @Resource
    DemandService demandService;

    //展示页面
    @RequestMapping("listView")
    public ModelAndView listView() {
        ModelAndView modelAndView = new ModelAndView();
        List<Project> projectList = projectService.list(new QueryWrapper<Project>()
                .select("id", "project_name"));
        modelAndView.addObject("listProject", projectList);
        modelAndView.setViewName("/demand/demand_list");
        return modelAndView;
    }

    // 获取标签信息
    @RequestMapping(value = "getLabelData", method = RequestMethod.GET)
    @ResponseBody
    public ResponseModel getLabelData() {
        List<Label> labelList = labelService.list();
        return ResponseModel.success(labelList);
    }

    // 保存需求数据
    @PostMapping("saveDemandData")
    @ResponseBody
    public ResponseModel saveDemandData(@RequestBody Map<String, String> map) {
        Demand demand = new Demand();
        demand.setProjectName(map.get("project"));
        demand.setDemandTime(map.get("date"));
        demand.setCreateTime(DateFormat.getTime());
        demand.setVersionId(map.get("version"));
        demand.setDemandInfo(map.get("context"));
        demand.setLabelName(map.get("label_name"));
        demand.setDemandStatus(Convert.toInt(map.get("demandStatus")));
        demand.setSumMonth(DateFormat.getDateMonth());
        boolean status = demandService.save(demand);
        //往项目表里存储需求时间和需求标签，方面后面页面渲染
        saveRedundancyData(map.get("label_name"), map.get("date"), map.get("project"));
        // User id  待完成
        if (status) {
            return ResponseModel.success("需求录入成功");
        } else {
            return ResponseModel.fail("需求录入失败");
        }
    }
    // 此函数是为了方便主界面1页面数据展示用的，有效缓解频繁取数据库数据
    public void saveRedundancyData(String label_name, String demandTime, String projectName) {
        Project project = projectService.getOne(new QueryWrapper<Project>().eq("project_name", projectName));
        String sum_demand_label = project.getSumDemandLabel();
        String sum_demand_time = project.getSumDemandTime();
        if (StrUtil.isNotEmpty(sum_demand_label)) {
            String insertLabelName = "";
            for (String label : label_name.split(",")) {
                boolean labelStatus = sum_demand_label.contains(label);
                if (!labelStatus) {
                    //如果不包含的情况下新增数据
                    insertLabelName += label + ",";
                }
            }
            project.setSumDemandLabel(sum_demand_label + insertLabelName);
        } else {
            project.setSumDemandLabel(label_name + ",");
        }
        if (StrUtil.isNotEmpty(sum_demand_time)) {
            String splitTime = demandTime.substring(0, 7) + ",";
            boolean timeStatus = sum_demand_time.contains(splitTime);
            if (!timeStatus) {
                project.setSumDemandTime(sum_demand_time + splitTime);
            }
        } else {
            project.setSumDemandTime(demandTime.substring(0, 7) + ",");
        }
        projectService.updateById(project);
    }

    // 列表数据
    @RequestMapping(value = "/getListData", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getListData(
            @RequestParam(value = "page") int page,
            @RequestParam(value = "limit") int limit) {
        IPage<Demand> demandPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        demandPage = demandService.page(demandPage, null);
        List<Demand> demandList = demandPage.getRecords();//获取数据，这里面还有当前页码数还有总数据参数
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", demandPage.getTotal());
        map.put("data", demandList);
        return map;
    }

    // 修改需求数据
    @PostMapping("edit")
    @ResponseBody
    public ResponseModel edit(@RequestBody JSONObject data) {
        Demand demand = new Demand();
        demand.setId(Convert.toInt(data.get("id")));
        demand.setProjectName(Convert.toStr(data.get("projectName")));
        demand.setDemandTime(Convert.toStr(data.get("demandTime")));
        demand.setLabelName(Convert.toStr(data.get("labelName")));
        demand.setDemandInfo(Convert.toStr(data.get("demandInfo")));
        demand.setVersionId(Convert.toStr(data.get("versionId")));
        demand.setDemandStatus(Convert.toInt(data.get("demandStatus")));
        boolean status = demandService.updateById(demand);
        if (status) {
            return ResponseModel.success("修改成功");
        } else {
            return ResponseModel.fail("修改失败");
        }
    }
}
